﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Threading;
using System.IO;
namespace ServerApp
{
   public class TCPservices
    {

       public const int buffer=1024;
       static ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
       public string GetLocalIP()// trả ra IPAddress 
	    {
	        string _IP = null;
	        // Resolves a host name or IP address to an IPHostEntry instance.
            // IPHostEntry - Provides a container class for Internet host address information.
	        System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
	 
	        // IPAddress class contains the address of a computer on an IP network.
	        foreach (System.Net.IPAddress _IPAddress in _IPHostEntry.AddressList)
	        {
	            // InterNetwork indicates that an IP version 4 address is expected
	            // when a Socket connects to an endpoint
	            if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
	            {
	                _IP = _IPAddress.ToString();
                  
	            }
	        }
            return _IP;
	    }
       public void respones(String ip)
       {
           Console.WriteLine("Connecting ..........");
           try
           {
               TcpClient client = new TcpClient();
               client.Connect(ip, 8080);
               Stream stream = client.GetStream();
               Console.WriteLine("connected !!! ");
                Console.WriteLine("Enter you String: ");
                string str = Dns.GetHostName();
                String ipLocal = GetLocalIP();
                String dataToSend = str + "," + ipLocal;
                byte[] data = encoding.GetBytes(dataToSend);
                stream.Write(data, 0, data.Length);
                stream.Close();
               client.Close();
           }
           catch (Exception e)
           {
               Console.WriteLine(e);
           }
           Console.Read();
       }
       public void respones(string ip, string thongtin)
       {
           try
           {
               TcpClient client = new TcpClient();
               client.Connect(ip, 8484);
               Stream stream = client.GetStream();
               byte[] data = encoding.GetBytes(thongtin);
               stream.Write(data, 0, data.Length);
               stream.Close();
               client.Close();
           }
           catch (Exception e)
           {
               MessageBox.Show(e.ToString());
           }
       }
   
        
    }
}
